package arithmetic.leecode_arthmetic;

/**
 * 合并两个有序链表
 * 方法：使用双指针
 *
 * <a href="https://leetcode.cn/problems/merge-two-sorted-lists/description/?envType=study-plan-v2&envId=top-100-liked">...</a>
 */
public class Solution21 {

    public static void main(String[] args) {

    }


    /**
     * 使用双指针解决
     * @param list1：链表1
     * @param list2：链表2
     * @return
     */
    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        if(list1 == null){
            return list2;
        }
        if(list2 == null){
            return list1;
        }

        ListNode resultNode = new ListNode(0);
        ListNode p = resultNode;
        while (list1!=null && list2!=null){

            if(list1.val < list2.val){
                    p.next = list1;
                    list1 =  list1.next;
            }else {
                p.next = list2;
                list2 = list1.next;
            }
        }
        if(list1!=null){
            p.next = list1;
        }
        if(list2!=null){
            p.next = list2;
        }

        return p.next;
    }

    public ListNode mergeTwoListsByRecusion(ListNode list1, ListNode list2) {
        if(list1 == null) return list2;
        if(list2 == null) return list1;

        if(list1.val < list2.val){
            list1.next = mergeTwoLists(list1.next,list2);
            return list1;
        }else {
            list2.next = mergeTwoLists(list1,list2.next);
        }
        return list2;
    }



        public class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
}




